import hotUpdate from 'react-native-ota-hot-update';
import {useCallback, useRef, useState} from 'react';
import {Alert, Platform} from 'react-native';
import ReactNativeBlobUtil from 'react-native-blob-util';
import VersionUtils from '@/utils/versionUtils';
import DeviceInfo from 'react-native-device-info';
import storage from '@/utils/storage';
import NativeLaunchManager from '~/specs/NativeLaunchManager';
export default (setNeedUpdate: (needUpdate: boolean) => void) => {
  const [progress, setProgress] = useState(0);
  const startUpdateRef = useRef<() => void>(null);
  // const startTimeRef = useRef<number | null>(null);

  // useEffect(() => {
  //   let animationFrameId: number;

  //   const duration = 3000; // 3秒

  //   const animate = (timestamp: number) => {
  //     if (startTimeRef.current === null) startTimeRef.current = timestamp;

  //     const elapsed = timestamp - startTimeRef.current;
  //     const progress = Math.min(elapsed / duration, 1); // 限制最大为 1

  //     setProgress(Math.floor(progress * 100));

  //     if (progress < 1) {
  //       animationFrameId = requestAnimationFrame(animate);
  //     }
  //   };

  //   animationFrameId = requestAnimationFrame(animate);

  //   return () => cancelAnimationFrame(animationFrameId);
  // }, []);

  const startUpdate = async (url: string, version: number) => {
    hotUpdate.downloadBundleUri(ReactNativeBlobUtil, url, version, {
      updateFail(message?: string) {
        Alert.alert('Update failed!', message, [
          {
            text: 'Cancel',
            style: 'cancel',
          },
        ]);
        setNeedUpdate(false)
      },
      updateSuccess() {
        storage.set('version', version);
        NativeLaunchManager.show()
      },
      progress(received, total) {
        const percent = (+received / +total) * 100;
        // LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        setProgress(+percent.toFixed(0));
      },
      restartAfterInstall: true,
      restartDelay: 0,
    });
  };
  const onCheckVersion = useCallback(async () => {
    return await fetch(
      'https://test-monitoring.tsun-ess.com/private/update.json',
    ).then(async data => {
      const result = await data.json();
      const currentVersion = storage.getString(
        'version',
        DeviceInfo.getVersion(),
      );
      if (VersionUtils.needUpdate(currentVersion, result.version)) {
        startUpdateRef.current = () => {
          startUpdate(
            Platform.OS === 'ios'
              ? result?.downloadIosUrl
              : result?.downloadAndroidUrl,
            result.version,
          );
        };
        return true;
      }
      return false;
    });
  }, []);
  return {
    progress,
    onCheckVersion,
    startUpdate: startUpdateRef.current,
  };
};
